package com.shadow.bus.main.search;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.shadow.bus.adapter.SimpleSearchKeyAdapter;
import com.shadow.bus.config.ItemFiled;
import com.shadow.bus.config.ItemType;
import com.shadow.bus.config.NetState;
import com.shadow.bus.config.PersistData;
import com.shadow.bus.config.ServiceUrl;
import com.shadow.bus.config.SpKey;
import com.shadow.bus.entity.OperationEntity;
import com.shadow.bus.entity.PartEntity;
import com.shadow.bus.entity.TroubleEntity;
import com.shadow.bus.entity.TroubleOperationEntity;
import com.shadow.bus.event.SearchResultEvent;
import com.tepth.shadow.ui.dialog.sweet.DialogDelegate;
import com.tepth.shadow.ui.dialog.sweet.SweetAlertDialogDelegate;
import com.tepth.shadow.ui.recycler.MultipleItemEntity;
import com.tepth.shadow.ui.recycler.RecyclerViewNoBugLinearLayoutManager;
import com.zhangyu.shadow.core.delegate.RxShadowDelegate;
import com.zhangyu.shadow.core.net.callback.IError;
import com.zhangyu.shadow.core.net.callback.ISuccess;
import com.zhangyu.shadow.core.net.rx.RxRestClient;
import com.zhangyu.shadow.core.util.storage.ShadowPreference;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import busfix.tepth.com.shadow_bus.R;
import busfix.tepth.com.shadow_bus.R2;
import butterknife.BindView;

/**
 * @author zhangyu
 * @date 2018/7/5
 */

public class SearchDelegate extends RxShadowDelegate {
    private static final String OPERATION = "operation";
    private static final String TROUBLE = "trouble";
    private static final String POSITION = "position";

    public static SearchDelegate newInstance(OperationEntity operationEntity,
                                             TroubleEntity troubleEntity,
                                             int position) {
        Bundle args = new Bundle();
        SearchDelegate fragment = new SearchDelegate();
        args.putSerializable(OPERATION, operationEntity);
        args.putSerializable(TROUBLE, troubleEntity);
        args.putInt(POSITION, position);
        fragment.setArguments(args);
        return fragment;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.et_search)
    EditText mEditTextSearch;
    @BindView(R2.id.id_tag_flow_layout)
    TagFlowLayout mTagFlowLayout;
    @BindView(R2.id.tv_action)
    TextView mTvAction;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.layout_empty)
    LinearLayout mLayoutEmpty;
    @BindView(R2.id.layout_key)
    LinearLayout mLayoutKey;
    @BindView(R2.id.recycler_view_key)
    RecyclerView mRecyclerViewKey;
    DialogDelegate mDialogDelegate;
    private SearchAdapter mSearchAdapter;
    private SimpleSearchKeyAdapter mSearchKeyAdapter;
    private OperationEntity mOperationEntity;
    private TroubleEntity mTroubleEntity;
    private int mPosition;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mOperationEntity = (OperationEntity) bundle.getSerializable(OPERATION);
            mTroubleEntity = (TroubleEntity) bundle.getSerializable(TROUBLE);
            mPosition = bundle.getInt(POSITION);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_search;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mDialogDelegate = new SweetAlertDialogDelegate(getContext());
        mToolbar.inflateMenu(R.menu.search);
        mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int i = item.getItemId();
                if (i == R.id.menu_search) {
                    search(mEditTextSearch.getText().toString().trim());
                }
                return true;
            }
        });
        mEditTextSearch.setHint("请输入要搜索的零部件");
        mEditTextSearch.setInputType(InputType.TYPE_CLASS_TEXT);
        mEditTextSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    search(mEditTextSearch.getText().toString().trim());
                    return true;
                }
                return false;
            }
        });
        mRecyclerView.setLayoutManager(new RecyclerViewNoBugLinearLayoutManager(getContext()));
        mSearchAdapter = new SearchAdapter(R.layout.item_text, null);
        mRecyclerView.setAdapter(mSearchAdapter);
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                postSearchData((MultipleItemEntity) adapter.getItem(position));
            }
        });
        mSearchAdapter.bindToRecyclerView(mRecyclerView);
        mSearchAdapter.setEmptyView(R.layout.view_adapter_empty);

        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getContext());
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        layoutManager.setAlignItems(AlignItems.STRETCH);
        mRecyclerViewKey.setLayoutManager(layoutManager);
        mSearchKeyAdapter = new SimpleSearchKeyAdapter(R.layout.view_tv, null);
        mRecyclerViewKey.setAdapter(mSearchKeyAdapter);
        mRecyclerViewKey.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                mEditTextSearch.append(" " + adapter.getItem(position));
            }
        });
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        if (PersistData.getInstance().getRecommendEntities() == null) {
            mDialogDelegate.showProgressDialog(false, "正在加载...");
            if (!NetState.IS_NET_CONNECT) {
                mDialogDelegate.stopProgressWithFailed("加载失败", "没有网络，请检查网络");
            } else {
                mDisposables.add(RxRestClient.builder()
                        .url(ServiceUrl.COMMON_COMPONENT)
                        .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                        .params("top", 20)
                        .success(new ISuccess() {
                            @Override
                            public void onSuccess(String response) {
                                List<MultipleItemEntity> list = new SearchDataConverter()
                                        .convert(response, new ArrayList<String>());
                                PersistData.getInstance().setRecommendEntities(list);
                                setCommonData(list);
                                mDialogDelegate.clearDialog();
                            }
                        })
                        .error(new IError() {
                            @Override
                            public void onError(int code, String msg) {

                            }
                        })
                        .build()
                        .get());
            }
        } else {
            setCommonData(PersistData.getInstance().getRecommendEntities());
        }
    }

    private void setCommonData(List<MultipleItemEntity> list) {
        final LayoutInflater inflater = LayoutInflater.from(getContext());
        final TagAdapter tagAdapter = new TagAdapter<MultipleItemEntity>(list) {
            @Override
            public View getView(FlowLayout parent, int position, MultipleItemEntity o) {
                TextView tv = (TextView) inflater.inflate(R.layout.view_tv,
                        parent, false);
                PartEntity partEntity = o.getField(ItemFiled.ITEM_OBJ);
                tv.setText(partEntity.getName());
                return tv;
            }
        };
        mTagFlowLayout.setAdapter(tagAdapter);
        mTagFlowLayout.setMaxSelectCount(1);
        mTagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                //TODO 需要知道选中的是哪个list里面的数据
                postSearchData((MultipleItemEntity) tagAdapter.getItem(position));
                return false;
            }
        });
    }

    private void search(String key) {
        if (!key.isEmpty()) {
            mSearchAdapter.setNewData(null);
            if (!NetState.IS_NET_CONNECT) {
                mSearchAdapter.setEmptyView(R.layout.view_adapter_no_net);
            } else {
                mSearchAdapter.setEmptyView(R.layout.view_adapter_loading);
                mDisposables.add(RxRestClient.builder()
                        .url(ServiceUrl.SEARCH_PART)
                        .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                        .params("name", key)
                        .success(new ISuccess() {
                            @Override
                            public void onSuccess(String response) {
                                ArrayList<String> keys = new ArrayList<>();
                                mSearchAdapter.setNewData(new SearchDataConverter()
                                        .convert(response, keys));
                                mSearchKeyAdapter.setNewData(keys);
                                mSearchAdapter.setEmptyView(R.layout.view_adapter_empty);
                            }
                        })
                        .error(new IError() {
                            @Override
                            public void onError(int code, String msg) {
                                mSearchAdapter.setEmptyView(R.layout.view_adapter_empty);
                            }
                        })
                        .build()
                        .get());
            }
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        pop();
        return true;
    }

    private void postSearchData(MultipleItemEntity multipleItemEntity) {
        if (mOperationEntity != null && mTroubleEntity != null) {
            TroubleOperationEntity entity = new TroubleOperationEntity();
            entity.setId(0);
            entity.setTroubleTypeName(mTroubleEntity.getName());
            entity.setTroubleTypeId(mTroubleEntity.getTroubleTypeId());
            entity.setTroubleId(mTroubleEntity.getId());
            if (mTroubleEntity.getClassification() != null) {
                entity.setClassificationId(mTroubleEntity.getClassification().getId());
                entity.setClassificationName(mTroubleEntity.getClassification().getName());
            }
            entity.setOperation(mOperationEntity);
            PartEntity partEntity = multipleItemEntity.getField(ItemFiled.ITEM_OBJ);
            if (multipleItemEntity.getItemType() == ItemType.TYPE_PART_ACCESSORY) {
                entity.setAccessory(partEntity);
            } else {
                entity.setComponent(partEntity);
            }
            entity.setUseCount(1);
            ArrayList<TroubleOperationEntity> troubleOperationEntities = mTroubleEntity.getListContent();
            if (troubleOperationEntities == null) {
                troubleOperationEntities = new ArrayList<>();
                mTroubleEntity.setListContent(troubleOperationEntities);
            }
            troubleOperationEntities.add(entity);
            EventBus.getDefault().post(new SearchResultEvent(entity, mPosition, mTroubleEntity));
            pop();
        }
    }
}
